from cocos import tiles, actions
from pyglet.window import key
from cocos.director import director
from object import *

GRAVITY=3000
JUMPSPEED=1000

class CCtrl(actions.Action, tiles.RectMapCollider):
	
	def start(self):
		self.ground=False
		self.keyboard=key.KeyStateHandler()
		director.window.set_handlers("normal_ctrl",self.keyboard)

	def stop(self):
		director.window.remove_handler("normal_ctrl",self.keyboard)
		self.keyboard=None
		self.target=None

	def step(self,dt):
		pobj=self.target
		scobj=GetScene(pobj.m_Scene)
		if not scobj:
			raise Exception("CCtrl Scene(%d) Not Exists"%pobj.m_Scene)
		dx,dy=pobj.m_vx,pobj.m_vy
		kb=self.keyboard
		dx=(kb[key.RIGHT]-kb[key.LEFT])*pobj.m_Speed*dt
		if not self.ground:
			dy-=GRAVITY*dt
		elif kb[key.SPACE]:
			dy=JUMPSPEED
		
		last=pobj.get_rect()
		new=last.copy()
		new.x+=dx
		new.y+=dy*dt

		dx,dy=self.collide_map(scobj.m_Map.m_RectMap,last,new,dy,dx)
		pobj.m_vx=dx
		pobj.m_vy=dy
		self.ground=bool(new.y==last.y)
		self.target.position=new.center

		scobj.SetFocus(*new.center)
